# etbox_service.py - 后台服务
# coder DarionDong

import os
import json
import socket
import threading
import time
from pathlib import Path
import requests

class ETBOXService:
    def __init__(self):
        self.config_file = os.path.join(os.path.expanduser("~"), ".etbox_service.json")
        self.socket_path = r"\\.\pipe\etbox_upload_pipe"  # Windows命名管道
        self.load_config()
        
    def load_config(self):
        """加载配置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.base_url = config.get('base_url', "http://127.0.0.1:8812")
        except Exception as e:
            print(f"加载配置失败: {e}")
            self.base_url = "http://127.0.0.1:8812"
    
    def save_config(self):
        """保存配置"""
        try:
            config = {'base_url': self.base_url}
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存配置失败: {e}")
    
    def check_service(self):
        """检查ETBOX服务状态"""
        try:
            response = requests.get(f"{self.base_url}/api/system_info", timeout=5)
            return response.status_code == 200
        except:
            return False
    
    def upload_file(self, file_path):
        """上传文件到ETBOX"""
        if not os.path.exists(file_path):
            return False, "文件不存在"
        
        if not self.check_service():
            return False, "ETBOX服务未启动"
        
        try:
            file_name = os.path.basename(file_path)
            file_size = os.path.getsize(file_path)
            
            # 实际文件上传
            with open(file_path, 'rb') as f:
                files = {'file': (file_name, f)}
                response = requests.post(
                    f"{self.base_url}/file/upload", 
                    files=files,
                    timeout=30
                )
            
            if response.status_code == 200:
                return True, f"文件上传成功: {file_name}"
            else:
                return False, f"上传失败: HTTP {response.status_code}"
                
        except Exception as e:
            return False, f"上传出错: {str(e)}"
    
    def handle_client_request(self, client_socket):
        """处理客户端请求"""
        try:
            # 接收文件路径
            data = client_socket.recv(1024).decode('utf-8').strip()
            if data:
                file_path = data
                print(f"收到上传请求: {file_path}")
                
                # 执行上传
                success, message = self.upload_file(file_path)
                
                # 返回结果
                result = json.dumps({"success": success, "message": message})
                client_socket.send(result.encode('utf-8'))
                
        except Exception as e:
            print(f"处理请求出错: {e}")
        finally:
            client_socket.close()
    
    def run(self):
        """运行服务"""
        print("ETBOX上传服务启动...")
        
        # 创建命名管道（Windows）
        try:
            import win32pipe
            import win32file
            import pywintypes
            
            # 创建命名管道
            pipe = win32pipe.CreateNamedPipe(
                self.socket_path,
                win32pipe.PIPE_ACCESS_DUPLEX,
                win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
                1, 65536, 65536,
                0,
                None
            )
            
            print(f"服务监听中: {self.socket_path}")
            
            while True:
                try:
                    # 等待客户端连接
                    win32pipe.ConnectNamedPipe(pipe, None)
                    print("客户端已连接")
                    
                    # 处理请求
                    try:
                        # 读取数据
                        data = win32file.ReadFile(pipe, 65536)
                        file_path = data[1].decode('utf-8').strip()
                        
                        if file_path:
                            print(f"处理上传: {file_path}")
                            success, message = self.upload_file(file_path)
                            
                            # 返回结果
                            result = json.dumps({"success": success, "message": message})
                            win32file.WriteFile(pipe, result.encode('utf-8'))
                            
                    except Exception as e:
                        print(f"处理请求出错: {e}")
                        error_result = json.dumps({"success": False, "message": str(e)})
                        win32file.WriteFile(pipe, error_result.encode('utf-8'))
                    
                    # 断开连接
                    win32pipe.DisconnectNamedPipe(pipe)
                    
                except pywintypes.error as e:
                    if e.args[0] == 109:  # 管道已关闭
                        print("客户端断开连接")
                        continue
                    else:
                        raise
                        
        except ImportError:
            print("错误: 需要安装pywin32库")
            input("按回车键退出...")